package com.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.entity.Department;
import com.hospital.entity.User;
import com.hospital.entity.Ward;
import com.hospital.mapper.WardMapper;
import com.hospital.service.DepartmentService;
import com.hospital.service.UserService;
import com.hospital.service.WardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 病房服务实现类
 *
 * @author Hospital Management System
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WardServiceImpl extends ServiceImpl<WardMapper, Ward> implements WardService {

    private final DepartmentService departmentService;
    private final UserService userService;

    @Override
    public List<Ward> getWards(String keyword, Long departmentId, Integer type, Integer floor) {
        QueryWrapper<Ward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like("ward_no", keyword)
                .or()
                .like("name", keyword)
            );
        }
        
        // 按科室ID筛选
        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        
        // 按病房类型筛选
        if (type != null) {
            queryWrapper.eq("type", type);
        }
        
        // 按楼层筛选
        if (floor != null) {
            queryWrapper.eq("floor", floor);
        }
        
        queryWrapper.orderByAsc("floor", "ward_no");
        List<Ward> wards = list(queryWrapper);
        
        // 填充关联信息
        fillRelatedInfo(wards);
        
        return wards;
    }

    @Override
    public List<Ward> getWardsByDepartment(Long departmentId) {
        QueryWrapper<Ward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department_id", departmentId)
                   .eq("status", 1) // 启用状态
                   .eq("deleted", 0)
                   .orderByAsc("floor", "ward_no");
        
        List<Ward> wards = list(queryWrapper);
        
        // 填充关联信息
        fillRelatedInfo(wards);
        
        return wards;
    }

    @Override
    public void updateBedOccupancy(Long wardId, Integer occupiedBeds) {
        Ward ward = getById(wardId);
        if (ward != null) {
            ward.setOccupiedBeds(occupiedBeds);
            updateById(ward);
            log.info("更新病房{}床位占用情况: {}/{}", wardId, occupiedBeds, ward.getTotalBeds());
        }
    }

    /**
     * 填充病房关联信息
     */
    private void fillRelatedInfo(List<Ward> wards) {
        if (wards == null || wards.isEmpty()) {
            return;
        }

        // 获取所有科室ID和护士ID
        List<Long> departmentIds = wards.stream()
                .map(Ward::getDepartmentId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());

        List<Long> nurseIds = wards.stream()
                .map(Ward::getNurseId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询科室信息
        Map<Long, Department> departmentMap = departmentIds.isEmpty() ? 
            Collections.emptyMap() : 
            departmentService.listByIds(departmentIds).stream()
                .collect(Collectors.toMap(Department::getId, dept -> dept));

        // 批量查询护士信息
        Map<Long, User> nurseMap = nurseIds.isEmpty() ? 
            Collections.emptyMap() : 
            userService.listByIds(nurseIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        // 填充关联信息
        wards.forEach(ward -> {
            // 填充科室名称
            if (ward.getDepartmentId() != null && departmentMap.containsKey(ward.getDepartmentId())) {
                Department department = departmentMap.get(ward.getDepartmentId());
                ward.setDepartmentName(department.getName());
            }

            // 填充护士姓名
            if (ward.getNurseId() != null && nurseMap.containsKey(ward.getNurseId())) {
                User nurse = nurseMap.get(ward.getNurseId());
                ward.setNurseName(nurse.getName());
            }
        });
    }

    /**
     * 填充单个病房关联信息
     */
    private void fillRelatedInfo(Ward ward) {
        if (ward == null) {
            return;
        }

        // 填充科室信息
        if (ward.getDepartmentId() != null) {
            Department department = departmentService.getById(ward.getDepartmentId());
            if (department != null) {
                ward.setDepartmentName(department.getName());
            }
        }

        // 填充护士信息
        if (ward.getNurseId() != null) {
            User nurse = userService.getById(ward.getNurseId());
            if (nurse != null) {
                ward.setNurseName(nurse.getName());
            }
        }
    }

    @Override
    public Ward getById(java.io.Serializable id) {
        Ward ward = super.getById(id);
        if (ward != null) {
            fillRelatedInfo(ward);
        }
        return ward;
    }
} 